package cn.edu.nju.software.action.user;

import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import cn.edu.nju.software.bean.show.UserShow;
import cn.edu.nju.software.bean.storage.User;
import cn.edu.nju.software.service.intf.UserService;
import cn.edu.nju.software.util.Constants;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class UserRegisterAction extends ActionSupport implements SessionAware, ServletResponseAware {
	
	private String signInName;
	private String password;
	private String rand;
	private UserService userService;
	private Map<String, Object> session;
	private HttpServletResponse response;

	public void setSignInName(String signInName) {
		this.signInName = signInName;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setRand(String rand) {
		this.rand = rand;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
		response.setCharacterEncoding("UTF-8");
	}

	public void register() throws Exception {
		String rightRand = (String) session.get(Constants.SESSION_RAND);
		if (!rightRand.equals(rand)) {
			response.getWriter().write("验证码错误！");
			return;
		}
		User user = new User(0, signInName, null, password, null, null, null, Constants.USER_NORMAL);
		int userID = userService.register(user);
		if (userID > 0) {
			user.setUserID(userID);
			session.put(Constants.SESSION_USER, new UserShow(user));
			response.getWriter().write(SUCCESS);
		} else {
			response.getWriter().write("此用户名已存在！");
		}
	}
	
}
